package com.homegoods.area.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.homegoods.area.R;
import com.homegoods.classify.model.TestBean.DatasBean.AddressListBean;
import com.kedll.library.adapter.MyArrayAdapter;
import com.kedll.library.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author slj
 * @date 2015/2/12
 */
public class SearchHotCitiesAdapter extends MyArrayAdapter<AddressListBean> implements Filterable {

    private MyFilter mFilter;

    public SearchHotCitiesAdapter(Context context) {
        super(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.area_hot_cities_child, null);
        }

        AddressListBean jo = getItem(position);

        TextView tv = (TextView) convertView;
        tv.setText(jo.toString());

        return convertView;
    }

    @Override
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new MyFilter();
        }
        return mFilter;
    }

    class MyFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint != null && constraint.length() > 0) {
                String prefixString = constraint.toString().toLowerCase();
                final List<AddressListBean> values = getValues();
                final int count = CollectionUtils.size(values);

                final ArrayList<AddressListBean> newValues = new ArrayList<>(count);

                for (AddressListBean v : values) {
                    String title = v.toString();
                    if (title.contains(prefixString)) {
                        newValues.add(v);
                    }
                }
                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.count > 0) {
                clear();
                addAll((List<AddressListBean>) results.values);
                notifyDataSetChanged();
            } else {
                clear();
                notifyDataSetInvalidated();
            }
        }
    }
}
